package com.be.beadmin.logging.aspect;


import com.be.beadmin.common.utils.SecurityUtils;
import com.be.beadmin.logging.entity.Log;
import com.be.beadmin.logging.service.LogService;
import com.be.beadmin.logging.util.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogAspect {

    private final LogService logService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public LogAspect(LogService logService) {
        this.logService = logService;
    }

    // 配置切入点
    @Pointcut("@annotation(com.be.beadmin.logging.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }


    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        Log log = new Log("INFO",System.currentTimeMillis() - currentTime.get());
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        logService.save(getUsername(), "", "",joinPoint, log);
        return result;
    }

    public String getUsername() {
        try {
            return SecurityUtils.getLoginUser().getName();
        }catch (Exception e){
            return "";
        }
    }

}
